﻿using Cl.Entity.DataBaseEntity.User;
using Cl.Repository;
using Cl.Service.ElsaWorkflow.Activity.ClAudit.Models;
using Cl.Service.ElsaWorkflow.Modes;
using Cl.Utils;
using Cl.Utils.Primitives.Const.Workflows;
using Elsa.ActivityResults;
using Elsa.Attributes;
using Elsa.Design;
using Elsa.Metadata;
using Elsa.Services.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Cl.Service.ElsaWorkflow.Activity.ClAudit
{
    [Trigger(Category = "ClActivitys", DisplayName = "审批", Description = "审批流", Outcomes = new[] { "同意", "拒绝" })]
    public class AuditActivity : Elsa.Services.Activity, IActivityPropertyOptionsProvider
    {
        #region Ui

        [ActivityInput(
        UIHint = ActivityInputUIHints.MultiText,
        DefaultSyntax = "Json",
        SupportedSyntaxes = new[] { "Json", "Liquid" },
        IsDesignerCritical = true,
        Label = "审批人账号")]
        public List<string> ApproveUsers { get; set; }

        [ActivityInput(IsBrowsable = false, Label = "备注")]
        public string Remark { get; set; }

        #endregion

        ClRepository<User> UserRepository => new ClRepository<User>();
        ClRepository<UserApproFlowMap> UserApproFlowMapRepository => new ClRepository<UserApproFlowMap>();
        
        /// <summary>
        /// 构造函数
        /// </summary>
        public AuditActivity()
        {

        }

        public object? GetOptions(PropertyInfo property)
        {
            var rv = new List<ComboSelectListItem>();

            return rv;
        }

        protected override IActivityExecutionResult OnExecute(ActivityExecutionContext context)
        {
            try
            {
                //context.Activity.ActivityBlueprint.Name
                var actionName = context.ActivityBlueprint.Name;
                List<UserApproFlowMap> insertList = new List<UserApproFlowMap>();


                if (ApproveUsers?.Count > 0)
                {
                    var dbUserList = UserRepository.GetList(x => ApproveUsers.Contains(x.Account));

                    foreach (var user in dbUserList)
                    {
                        insertList.Add(new UserApproFlowMap()
                        {
                            ApproflowId = context.WorkflowInstance.Id,
                            ApproflowType = ApproflowStateConst.WAITING,
                            UserId = user.Id,
                            Ispass = false,
                            FlowNode = actionName,
                            Remark = string.Empty,
                            Timestamp = DateTime.Now,

                            CreateId = GlobalUserManager.UserId,
                            CreateTime= DateTime.Now,
                            UpdateId = GlobalUserManager.UserId,
                            UpdateTime = DateTime.Now,
                        });
                    }


                }
                var result = UserApproFlowMapRepository.AsInsertable(insertList).ExecuteCommand() > 0;

            }
            catch { }
            return Suspend();
        }

        protected override IActivityExecutionResult OnResume(ActivityExecutionContext context)
        {
            WorkFlowAuditInput input = context.Input as WorkFlowAuditInput;
            Remark = input?.Remark;
            var activeName = context.ActivityBlueprint.Name;
            var entityId = input.EntityId;//context.ContextId;

            //ApprovedBy = input.CurrentUser.Name + "(" + input.CurrentUser.ITCode.ToLower() + ")";
            if (input?.Action == "同意" || input?.Action == "拒绝")
            {
                try
                {
                    List<UserApproFlowMap> updateList = new List<UserApproFlowMap>();
                    var existList = UserApproFlowMapRepository.GetList(x =>
                    x.ApproflowId == context.WorkflowInstance.Id &&
                    x.FlowNode == activeName &&
                    x.ApproflowType == ApproflowStateConst.WAITING);
                    foreach (var item in existList)
                    {
                        switch (input?.Action)
                        {
                            case "同意":
                                item.Ispass = true;
                                break;
                            case "拒绝":
                                item.Ispass = false;
                                break;
                            default:
                                item.Ispass = false;
                                break;
                        }

                        item.UpdateId = GlobalUserManager.UserId;
                        item.UpdateTime = DateTime.Now;
                        if (item.UserId == input.UserId)
                        {
                            item.ApproflowType = ApproflowStateConst.APPROVED;
                            item.Timestamp = DateTime.Now;
                            item.EntityId = input.EntityId;
                            item.Remark = input.Remark;
                            updateList.Add(item);
                        }
                        else
                        {
                            item.ApproflowType = ApproflowStateConst.CC;
                            item.Timestamp = DateTime.Now;
                            item.EntityId = input.EntityId;
                            updateList.Add(item);
                        }
                    }

                    var commandResult = UserApproFlowMapRepository.AsUpdateable(updateList).UpdateColumns(it => new
                    {
                        it.Ispass,
                        it.Timestamp,
                        it.EntityId,
                        it.UpdateTime,
                        it.UpdateId,
                        it.ApproflowType,
                        it.Remark
                    }).ExecuteCommand() > 0;

                }
                catch { }

                return Outcome(input?.Action);

            }
            else
            {
                return Suspend();
            }
        }
    }
}
